package com.midian.common.pay.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.midian.common.exception.BizException;
import com.midian.common.pay.alipay.util.AlipayNotify;
import com.midian.common.pay.common.util.iorder.OpOrder;
import com.midian.common.pay.tenpay.AccessTokenRequestHandler;
import com.midian.common.pay.tenpay.util.ConstantUtil;
import com.midian.common.pay.tenpay.util.WXUtil;
import com.midian.common.pay.tenpay.xmlutil.FormatXmlProcess;
import com.midian.common.pay.tenpay.xmlutil.ReceiveXmlUtils;
import com.midian.common.pay.tenpay.xmlutil.WechatUtils;
import com.midian.common.pay.vo.WXNotifyOrder;
import com.midian.common.pay.vo.WXPrepayBack;
import com.midian.common.utils.StringUtil;
import com.midian.model.activity.Activity;
import com.midian.model.activity.ActivityUser;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public abstract class PayUtils {
	
	private static final Logger LOG = Logger.getLogger(PayUtils.class);
	
	/**支付类型，1：支付宝*/
	public static Integer PAY_TYPE_ALI = 1;
	/**支付类型，2：微信*/
	public static Integer PAY_TYPE_WX = 2;
	
	/**处理状态，1：待处理*/
	public static Integer OP_STATUS_WAIT = 1;
	/**处理状态，2：已处理*/
	public static Integer OP_STATUS_OPED = 2;
	
	/**支付状态，1：待支付*/
	public static Integer PAY_STATUS_WAIT = 1;
	/**支付状态，2：已支付*/
	public static Integer PAY_STATUS_PAYED = 2;
	/**支付状态，3：支付失败*/
	public static Integer PAY_STATUS_FAILED = 3;
	
	/**
	 * 获取预支付订单JSON
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param productDesc 商品描述
	 * @param opOrder 处理订单接口对象
	 * @return
	 */
	public static JSONObject getWeiXinJSON(HttpServletRequest request, HttpServletResponse response,String orderNo,Double orderPrice ,Date orderCreateTime, String productDesc) throws Exception {
		
		    JSONObject wechatParameterJson = null;
		    //封装微信支付的参数信息
			//组装微信支付的参数
			//网关地址
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
			response.resetBuffer();
			response.setHeader("ContentType", "text/xml");
			//---------------------------------------------------------
			//微信支付请求示例，商户按照此文档进行开发即可 
			//---------------------------------------------------------

			//接收财付通通知的URL
			String notify_url = basePath + "/pay_wx_callback"; //注意：这是本服务器定义的微信回调接口地址
			//订单号，此处用时间加随机数生成，商户根据自己情况调整，只要保持全局唯一就行
			//---------------生成订单号 结束------------------------
			
			String token = AccessTokenRequestHandler.getAccessToken(); //获取token值 
			//String nonceStr = StringUtil.getRandomString(32); //随机32位字符串
			if (!"".equals(token)) {
				Map<String, String> params = new HashMap<String, String>();
				params.put("item", productDesc); //商品名称
				params.put("orderSn", orderNo); //订单号
				params.put("total", String.valueOf(orderPrice)); //应付金额
				params.put("ip", request.getRemoteAddr()); //下单者IP
				params.put("notifyUrl", notify_url);
				params.put("nonceStr", StringUtil.getRandomString(32)); //随机32位字符串
				params.put("createTime", new SimpleDateFormat("yyyyMMddHHmmss").format(orderCreateTime)); //订单生成时间
				
				String msg = FormatXmlProcess.formatXmlRequestPrepay(params);
				//预付订单对象
				WXPrepayBack wxPrepay = new WXPrepayBack();
				//微信支付生成订单的预付信息
				wxPrepay = WechatUtils.getWXPrepay(msg);
				//获取prepayId
				String prepayId = wxPrepay.getPrepay_id();
				//响应给客户端的参数
				LOG.error("prepayId:"+prepayId);
				if (StringUtils.isNotBlank(prepayId)) {
					//输出参数列表
					/*ClientRequestHandler clientHandler = new ClientRequestHandler(request, response);//返回客户端支付参数的请求类
					clientHandler.setParameter("appid", ConstantUtil.APP_ID);
					clientHandler.setParameter("noncestr", StringUtil.getRandomString(32));
					clientHandler.setParameter("package", "Sign=WXPay");
					clientHandler.setParameter("partnerid", ConstantUtil.PARTNER);
					clientHandler.setParameter("prepayid", prepayId);
					clientHandler.setParameter("timestamp", WXUtil.getTimeStamp());
					//生成签名
					String sign = clientHandler.createSHA1Sign();
					clientHandler.setParameter("sign", sign);

					JSONObject xml_body = clientHandler.getXmlBody();
					json.put("wechatParameter", xml_body);*/
					
					SortedMap<String, Object> sortMap = new TreeMap<String, Object>();
					sortMap.put("appid", ConstantUtil.APP_ID);
					sortMap.put("noncestr", StringUtil.getRandomString(32)); //随机32位字符串);
					sortMap.put("package", "Sign=WXPay");
					sortMap.put("partnerid", ConstantUtil.PARTNER);
					sortMap.put("prepayid", prepayId);
					sortMap.put("timestamp", WXUtil.getTimeStamp());
					String sign = StringUtil.createSign(sortMap); //签名
					
					wechatParameterJson = JSONObject.fromObject(sortMap);
					wechatParameterJson.put("sign", sign);
					
					//LOG.error(wechatParameterJson.toString());
				} else {
					throw new BizException("错误：获取prepayId失败");
				}
			} else {
				throw new BizException("错误：获取不到Token");
			}
		return wechatParameterJson;
	}
	
	/**
	 * 支付宝回调
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param opOrder 处理订单接口对象
	 */
	public static void aliCallback(HttpServletRequest request, HttpServletResponse response, OpOrder opOrder) {
		LOG.debug("===============【PayUtils】进入支付宝payutils.alicallback方法================");
		ServletOutputStream out=null;
		try {
			out = response.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map requestParams = request.getParameterMap();
		LOG.debug("==============【PayUtils】从request中获取支付宝返回requestParams=============="+requestParams);
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			params.put(name, valueStr);
		}
		JSONArray array = JSONArray.fromObject(params);
		String payInfo = array.toString();
		LOG.debug("===============【PayUtils】获取支付宝返回params的Json字符串================payInfo="+payInfo);
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
		String out_trade_no = ""; //商户订单号
		String trade_status = ""; //交易状态
		String trade_no = ""; //支付宝交易号
		String total_fee = "0.0";
		try {
			out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
			trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
			total_fee = new String(request.getParameter("total_fee").getBytes("ISO-8859-1"),"UTF-8");
			LOG.debug("=======【PayUtils】从Json串中取出以下信息==========");
			LOG.debug("=======【PayUtils】out_trade_no=========="+out_trade_no);
			LOG.debug("=======【PayUtils】trade_no=========="+trade_no);
			LOG.debug("=======【PayUtils】trade_status=========="+trade_status);
			LOG.debug("=======【PayUtils】total_fee=========="+total_fee);
		} catch (UnsupportedEncodingException e) {
			LOG.debug("========【PayUtils】=========="+e.getMessage());
		}
		//获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表
		try {
			if(AlipayNotify.verify(params)){//验证成功
				LOG.error("=======【PayUtils】消息来源支付宝验证成功==========");
				if("TRADE_FINISHED".equals(trade_status)){
					
					LOG.debug("=======【PayUtils】trade_status=========="+trade_status);
					//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					LOG.debug("=======【PayUtils】继续回调postOrdered==========");
					opOrder.postOrdered(Double.valueOf(total_fee), PAY_STATUS_PAYED, payInfo, out_trade_no, trade_no);
					out.println("success");
					//注意：
					//该种交易状态只在两种情况下出现
					//1、开通了普通即时到账，买家付款成功后。
					//2、开通了高级即时到账，从该笔交易成功时间算起，过了签约时的可退款时限（如：三个月以内可退款、一年以内可退款等）后。
				} else if ("TRADE_SUCCESS".equals(trade_status)){
					LOG.debug("=======【PayUtils】trade_status=========="+trade_status);
					//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//如果有做过处理，不执行商户的业务程序
					LOG.debug("=======【PayUtils】继续回调postOrdered==========");
					opOrder.postOrdered(Double.valueOf(total_fee), PAY_STATUS_PAYED, payInfo, out_trade_no, trade_no);
					out.println("success");
					//注意：
					//该种交易状态只在一种情况下出现——开通了高级即时到账，买家付款成功后。
				}else if("TRADE_CLOSED".equals(trade_status)){
					LOG.debug("=======【PayUtils】trade_status=========="+trade_status);
					LOG.debug("=======【PayUtils】继续回调postOrdered==========");
					opOrder.postOrdered(Double.valueOf(total_fee), PAY_STATUS_FAILED, payInfo, out_trade_no, trade_no);
					out.println("fail");
				}
			}else{//验证失败
				out.println("fail");
			}
		}catch (IOException e) {
			LOG.error("=======【PayUtils】AlipayNotify.verify(params)这个地方为false=========="+e.getMessage());
		}
	}
	
	/**
	 * 微信支付回调
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param opOrder 处理订单接口对象
	 * @throws IOException 
	 * @throws Exception
	 */
	public static void wxCallback(HttpServletRequest request, HttpServletResponse response, OpOrder opOrder) throws IOException{
		LOG.debug("===============【PayUtils】进入微信payutils.wxcallback方法================");
		String xml = "";
		try(InputStream is = request.getInputStream()) {
			xml = ReceiveXmlUtils.getStreamToString(is); // 即为接收到微信端发送过来的xml数据
		} catch (IOException e) {
			LOG.error(e.getMessage());
		}
		LOG.debug("===============【PayUtils】接收到从微信端发过来的xml数据================"+xml);
		if(StringUtils.isNotBlank(xml)) {
			LOG.debug("===============【PayUtils】开始解析以上xml为微信通知对象================");
			WXNotifyOrder notifyOrder = ReceiveXmlUtils.getMsgEntity(xml, WXNotifyOrder.class);
			if (notifyOrder != null && "SUCCESS".equals(notifyOrder.getReturn_code())&& "SUCCESS".equals(notifyOrder.getResult_code())) {
				LOG.debug("===============【PayUtils】如果微信通知对象不为空并且返回状态码和业务处理码都返回正常================");
				LOG.debug("===============【PayUtils】继续回调postOrdered================");
				opOrder.postOrdered(Double.parseDouble(notifyOrder.getTotal_fee()), PAY_STATUS_PAYED, 
						notifyOrder.getAttach(), notifyOrder.getOut_trade_no(), notifyOrder.getTransaction_id());
				
				
				response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
			} else {
				StringBuilder sb = new StringBuilder("查询验证签名失败或业务错误，");
				sb.append(" retCode: ").append(notifyOrder.getReturn_code())
				  .append(" resultCode: ").append(notifyOrder.getResult_code())
				  .append(" retMsg: ").append(notifyOrder.getReturn_msg());
				//错误时，返回结果未签名，记录retcode、retmsg看失败详情。
				LOG.debug("==========【PayUtils】==========="+sb.toString());
			}
		}
	}
	
	/**
	 * 微信支付回调
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param opOrder 处理订单接口对象
	 * @throws Exception
	 */
	/*public static void wxCallback(HttpServletRequest request, HttpServletResponse response, OpOrder opOrder){
		//商户号
		String partner = ConstantUtil.PARTNER;
		//密钥
		String key = ConstantUtil.PARTNER_KEY;
		//创建支付应答对象
		ResponseHandler resHandler = new ResponseHandler(request, response);
		resHandler.setKey(key);
		//判断签名
		if(resHandler.isTenpaySign()) {
			//通知id
			String notify_id = resHandler.getParameter("notify_id");
			//创建请求对象
			RequestHandler queryReq = new RequestHandler(null, null);
			//通信对象
			TenpayHttpClient httpClient = new TenpayHttpClient();
			//应答对象
			ClientResponseHandler queryRes = new ClientResponseHandler();
			//通过通知ID查询，确保通知来至财付通
			queryReq.init();
			queryReq.setKey(key);
			queryReq.setGateUrl("https://gw.tenpay.com/gateway/verifynotifyid.xml");
			queryReq.setParameter("partner", partner);
			queryReq.setParameter("notify_id", notify_id);
			try {
				//通信对象
				httpClient.setTimeOut(5);
				//设置请求内容
				httpClient.setReqContent(queryReq.getRequestURL());
				//后台调用
				if(httpClient.call()) {
					//设置结果参数
					queryRes.setContent(httpClient.getResContent());
					queryRes.setKey(key);
					//获取返回参数
					String retcode = queryRes.getParameter("retcode");
					String trade_state = queryRes.getParameter("trade_state");
					String trade_mode = queryRes.getParameter("trade_mode");
					//判断签名及结果
					if(queryRes.isTenpaySign() && "0".equals(retcode) && "0".equals(trade_state) && "1".equals(trade_mode)) {
						//取结果参数做业务处理
						String out_trade_no = queryRes.getParameter("out_trade_no"); //商户订单号
						String tradeNo = queryRes.getParameter("transaction_id"); //微信订单号
						String total_fee = queryRes.getParameter("total_fee");
						Double totalFee = Double.parseDouble(total_fee) / 100; //已支付金额
						total_fee = String.valueOf(totalFee); 
						//System.out.println("out_trade_no:" + out_trade_no + " transaction_id:" + tradeNo);
						//System.out.println("trade_state:" + queryRes.getParameter("trade_state")+ " total_fee:" + total_fee);
				        //如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
						//System.out.println("discount:" + queryRes.getParameter("discount")+ " time_end:" + queryRes.getParameter("time_end"));
						
						//处理数据库逻辑
						//注意交易单不要重复处理
						//注意判断返回金额
						opOrder.postOrdered(totalFee, OP_STATUS_OPED, PAY_STATUS_PAYED, queryRes.getAllParameters().toString(), out_trade_no, tradeNo);
						resHandler.sendToCFT("Success");
					} else{
						//错误时，返回结果未签名，记录retcode、retmsg看失败详情。
						LOG.error("查询验证签名失败或业务错误" + "retcode:" + queryRes.getParameter("retcode")+ " retmsg:" + queryRes.getParameter("retmsg"));
					}
				} else {
					//有可能因为网络原因，请求已经处理，但未收到应答。
					LOG.error("后台调用通信失败" + httpClient.getResponseCode() + "" + httpClient.getErrInfo());
				}
			} catch(Exception e) {
				LOG.error(e.getMessage());
			}
		}
		else{
			LOG.error("通知签名验证失败");
		}
	}*/
}
